

<template>
  <el-input v-model="message"></el-input>
  <el-button @click="sendMessage">发送</el-button>
  <el-button @click="connectionWebSocket">连接</el-button>
</template>

<script  lang="ts">
import Cookie from "../utils/cookies.ts";

interface ChatMessage {
  content: string;
  sender: string;
  receiver:string;
  timestamp: string;
}

// 连接WebSocket


// 发送消息

const wsUrl = 'ws://localhost:8080/chat';



export default {
  data() {
    return {
      message: '',
      messages: [] as ChatMessage[],
      isConnected: false,
      ws: null as any,
    }
  },
  
  created() {
    this.connectionWebSocket()
  },
  methods: {
    connectionWebSocket() {
      const token = Cookie.get('token');
      const wsUrlWithToken = `${wsUrl}?token=${token}`;
      this.ws = new WebSocket(wsUrlWithToken)
      this.ws.onopen = () => {
        console.log('WebSocket连接已打开')
        this.isConnected = true
      }
      this.ws.onmessage = (event : any) => {
        const data = JSON.parse(event.data)
        this.messages.push(data)
        console.log('WebSocket收到消息：', data)
      }
      this.ws.onclose = () => {
        console.log('WebSocket连接已关闭')
        this.isConnected = false
      }
    },

    sendMessage() {
      if (!this.isConnected) {
        console.error('WebSocket连接未建立')
        return
      }

      const message : ChatMessage = {
        content: this.message,
        sender: Cookie.get('userName') as string,
        receiver: 'all',
        timestamp: new Date().toLocaleString()
      }
      this.messages.push(message)
      this.ws.send(JSON.stringify(message))
    }


  }
}


</script>

<style scoped>

</style>